package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowow.comment.domain.TravelComment;
import cn.wolfcode.luowow.comment.query.TravelCommentQuery;
import cn.wolfcode.luowow.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 查看游记
 */
@Controller
@RequestMapping("travel")
public class TravelController {

    @Reference
    private ITravelService travelService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Reference
    private ITravelCommentService travelCommentService;

    @RequestMapping("")
    public String index(Model model, @ModelAttribute("qo") TravelQuery qo){

        model.addAttribute("pageInfo",travelService.query(qo));

        return "travel/list";

    }

    //写游记
    @RequestMapping("/input")
    public String input(Model model,Long id){//这里的id是后期回显需要
        //dests 查询这个深度下的内容共享

        List<Destination> dests = destinationService.getDestsByDeep(3);
        model.addAttribute("dests",dests);

        if(id !=null){
            Travel travel = travelService.get(id);
            TravelContent content = travelService.getContent(id);
            travel.setTravelContent(content);
            model.addAttribute("tv",travel);
        }
        return "travel/input";
    }

    @Value("${file.path}")
    private String BasePath;
    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, BasePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

    //增加或修改
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo userInfo){

        //判断是否登录
        if(userInfo == null){
            throw new LogicException("请检查是否登录");
        }
        travel.setAuthor(userInfo);

        //这里传过来的应该是用户刚刚登录时候的id
        Long id = travelService.saveOrUpdate(travel);
        return AjaxResult.SUCCESS.addData(id);
    }
    @RequestMapping("/info")
    @ResponseBody
    public Object info(@UserParam UserInfo userInfo){

        //springMvc的解析器cookie 将token解析userInfo对象
        return userInfo;
    }
    @RequestMapping("/save")
    @ResponseBody
    public Object save(UserInfo userInfo){

        //springMvc的解析器cookie 将token解析userInfo对象
        return userInfo;
    }

    @RequestMapping("/detail")
    public String detail(Model model,Long id,@UserParam UserInfo userInfo){
        //显示首页
        Travel detail = travelService.get(id);
        TravelContent travelContent = travelService.getContent(id);
        detail.setTravelContent(travelContent);
        model.addAttribute("detail",detail);

        //查询当前篇游记的目的地， 关联查询目的地的父目的地， 显示当前目的地的封面与名称
        List<Destination> toasts = destinationService.getToasts(detail.getDest().getId());
        Destination dest = toasts.remove(toasts.size() - 1);
        model.addAttribute("dest",dest);
        model.addAttribute("toasts",toasts);

        //根据当前篇游记的目的地查询该目的地下阅读量为前3的攻略，循环播放
        model.addAttribute("sds",strategyDetailService.queryViewNumTop3
                (detail.getDest().getId()));

        //根据当前篇游记的目的地查询该目的地下阅读量为前3的游记，循环播放
        model.addAttribute("ts",travelService.queryViewNumTop3
                (detail.getDest().getId()));
        if(userInfo != null){
            Long authorId = travelService.getAuthorId(id);
            System.out.println(authorId);
            System.out.println(userInfo.getId());
            if(authorId.equals(userInfo.getId())){
                model.addAttribute("sb",true);
            }else {
                model.addAttribute("sb",false);
            }
        }else {
            model.addAttribute("sb",false);
        }

        //查询游记评论的列表
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(id);
        qo.setPageSize(Integer.MAX_VALUE);//不分页

        Page page = travelCommentService.query(qo);
        model.addAttribute("list",page.getContent());

        return "travel/detail";
    }

    @RequestMapping("/commentAdd")
    public String commentAdd(Model model,TravelComment comment,@UserParam UserInfo userInfo,int floor){

        comment.setUserId(userInfo.getId());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setLevel(userInfo.getLevel());
        comment.setCity(userInfo.getCity());
        comment.setUsername(userInfo.getNickname());


        //游记评论的添加
        TravelComment comment1 = travelCommentService.saveOrUpdate(comment);

        //当前评论
        model.addAttribute("c",comment1);

        model.addAttribute("floor",travelCommentService.getCount(comment.getTravelId())); //当前评论
        return "travel/commentTpl";
    }
}
